package icu.lookyousmileface.http;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

/**
 * @author shenj
 * @title: NettyServerTerminal
 * @projectName NettyPro
 * @date 2020/12/4 18:50
 */
public class NettyServerTerminal {
    /**
     * @author shenj
     * @title: init
     * @date 2020/12/5  12:00
     * ready Configuration
     */
    private static final int port = 6633;
    private static final EventLoopGroup mainLoop = new NioEventLoopGroup();
    private static final EventLoopGroup workerLoop = new NioEventLoopGroup();
    private static final ServerBootstrap startServerConfiguration = new ServerBootstrap();
    private static ChannelPipeline channelPipeline = null;
    private static URI uri = null;

    /**
     * @author shenj
     * @title: main
     * @date 2020/12/5  12:01
     * run main
     */
    public static void main(String[] args) throws Exception {
        try {
            startServerConfiguration.group(mainLoop, workerLoop)
                    .channel(NioServerSocketChannel.class)
                    //workerHandler is init
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {

                            channelPipeline = ch.pipeline();
                            channelPipeline.addLast("MyHttpServerCodec", new HttpServerCodec());
                            channelPipeline.addLast(new SimpleChannelInboundHandler<HttpObject>() {

                                @Override
                                protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
                                    if (msg instanceof HttpRequest) {
                                        System.out.println("一个新的客户端来临：" + ctx.channel().remoteAddress());
                                        HttpRequest httpRequest = (HttpRequest) msg;
                                        uri = new URI(httpRequest.uri());
                                        if ("/favicon.ico".equals(uri.getPath())) {
                                            System.out.println("客户端：" + ctx.channel().remoteAddress() + ",请求的此类资源不可达!");
                                            return;
                                        }

                                        ByteBuf dataBuf = Unpooled.copiedBuffer("<h1>This is a Mark!Hi,</h1>" + ctx.channel().remoteAddress().toString().substring(1), CharsetUtil.UTF_8);

                                        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, dataBuf);
                                        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html;charset=utf-8");
                                        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, dataBuf.readableBytes());

                                        ctx.writeAndFlush(response);
                                    }
                                }
                            });
                        }
                    });

            System.out.println("Server is ready....");

            ChannelFuture channelFuture = startServerConfiguration.bind(port).sync();

            channelFuture.channel().closeFuture().sync();

        } finally {
            mainLoop.shutdownGracefully();
            workerLoop.shutdownGracefully();
        }
    }
}
